package com.example.flower_shop.websocket;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;


/**
 * websocket处理器
 */
@Component
@Slf4j
public class MyWebsocketHandler implements WebSocketHandler {
    @Resource
    private WebSocket webSocket;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        webSocket.handleOpen(session);
    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        webSocket.handleMessage(session, message.getPayload().toString());
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        webSocket.HandleError(session, exception);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        webSocket.handleClose(session);
        if (closeStatus.getCode() != 1000) {
            log.warn("发生异常：" + closeStatus.getReason() + "状态码为：" + closeStatus.getCode());
        }
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}
